//
//  BBClockViewController.swift
//  BBLinkiOSProject
//
//  Created by liuzhu on 2018/12/3.
//  Copyright © 2018 liuzhu. All rights reserved.
//

import SVProgressHUD
import UIKit
class BBClockViewController: UIViewController {
    @IBOutlet var distanceLabel: UILabel!
    @IBOutlet var timesLabel: UILabel!
    @IBOutlet var timeLabel: UILabel!
    @IBOutlet var dayPicture: UIImageView!
    @IBOutlet var dayDescription: UITextView!
    var day: BBDay?
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
    }

    override func viewWillAppear(_ animated: Bool) {
        let distanceK = Int(truncating: (day?.totalDistance ?? 0)) / 1000
        let distanceM = (Int(truncating: (day?.totalDistance ?? 0)) % 1000) / 100
        distanceLabel.text = "\(distanceK).\(distanceM)Km"
        timesLabel.text = "\(day?.times ?? 0)"
        timeLabel.text = "\((Int(truncating: (day?.totalTime)!) / 3600))H,\((Int(truncating: (day?.totalTime)!) % 3600) / 60)M,\(Int(truncating: (day?.totalTime)!) % 60)S"
    }
    
    private func setUI() {
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Clock", style: UIBarButtonItem.Style.plain, target: self, action: #selector(clockAction))
    }

    @objc private func clockAction() {
        print(#function)
        let path = "day/clock.do"
        let params = ["token": BBUser.loadUser()?.token, "userId": BBUser.loadUser()?.userId, "dayId": day?.dayId, "description": dayDescription.text]
        BBUploadImage.shareBBUploadImage().upload(path: path, params: params as [String: AnyObject], image: dayPicture.image!, maxSizeByte: 50 * 1024) { isSuccess in
            let result = isSuccess
            if result {
                self.navigationController?.popViewController(animated: true)
            } else {
                SVProgressHUD.showInfo(withStatus: "failed")
            }
            SVProgressHUD.dismiss()
        }
    }

    @IBAction func addImageAction(_ sender: UIButton) {
        present(selectorController, animated: true, completion: nil)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dayDescription.resignFirstResponder()
    }

    // MARK: 用于弹出选择的对话框界面
    var selectorController: UIAlertController {
        let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        controller.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil)) // 取消按钮
        controller.addAction(UIAlertAction(title: "拍照选择", style: .default) { _ in
            self.selectorSourceType(type: .camera)
        }) // 拍照选择
        controller.addAction(UIAlertAction(title: "相册选择", style: .default) { _ in
            self.selectorSourceType(type: .photoLibrary)
        }) // 相册选择
        return controller
    }
    //
    func selectorSourceType(type: UIImagePickerController.SourceType) {
        let vc = UIImagePickerController()
        vc.delegate = self
        vc.sourceType = type
        // 打开图片选择器
        present(vc, animated: true, completion: nil)
    }
}

extension BBClockViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
    // MARK: 图片选择器界面
    var imagePickerController: UIImagePickerController {
        let imagePicket = UIImagePickerController()
        imagePicket.delegate = self
        imagePicket.sourceType = .photoLibrary
        return imagePicket
    }

    // MARK: 当图片选择器选择了一张图片之后回调
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        dismiss(animated: true, completion: nil) // 选中图片, 关闭选择器...这里你也可以 picker.dismissViewControllerAnimated 这样调用...但是效果都是一样的...
        dayPicture.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage // 显示图片
        dayPicture.contentMode = .scaleAspectFit
    }

    // MARK: 当点击图片选择器中的取消按钮时回调
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil) // 效果一样的...
    }

    // 键盘事件
    func textViewDidBeginEditing(_ textView: UITextView) {
        animateViewMoving(up: true, moveValue: 260)
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        animateViewMoving(up: false, moveValue: 260)
    }

    func animateViewMoving(up: Bool, moveValue: CGFloat) {
        let movementDuration: TimeInterval = 0.3
        let movement: CGFloat = (up ? -moveValue : moveValue)
        UIView.beginAnimations("animateView", context: nil)
        UIView.setAnimationBeginsFromCurrentState(true)
        UIView.setAnimationDuration(movementDuration)
        view.frame = view.frame.offsetBy(dx: 0, dy: movement)
        UIView.commitAnimations()
    }
}
